package com.example.demo.hystrix;


import com.netflix.hystrix.HystrixCommand;
import com.netflix.hystrix.HystrixCommandGroupKey;
import com.netflix.hystrix.HystrixCommandKey;
import com.netflix.hystrix.HystrixCommandProperties;
import com.netflix.hystrix.HystrixThreadPoolKey;
import com.netflix.hystrix.HystrixThreadPoolProperties;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;

public class GetCourseServiceCommand extends HystrixCommand<String> {

    private CourseService courseService= new CourseService();


    protected GetCourseServiceCommand() {
        super(setter());
    }

   private static Setter setter(){
       //服务分组,配置全局唯一分组名称，默认类名
       HystrixCommandGroupKey groupKey= HystrixCommandGroupKey.Factory.asKey("course");
       //服务标识，配置全局唯一标识名称
       HystrixCommandKey commandKey= HystrixCommandKey.Factory.asKey("getCourse");
       //线程池名称，默认分组名
       HystrixThreadPoolKey threadPoolKey= HystrixThreadPoolKey.Factory.asKey("course-pool");
       //配置线程池
       HystrixThreadPoolProperties.Setter poolProperties= HystrixThreadPoolProperties.Setter()
               .withCoreSize(5)
               .withKeepAliveTimeMinutes(5)//空闲线程的生存时间
               .withMaxQueueSize(1000)//线程池队列最大大小
               .withQueueSizeRejectionThreshold(1000);//这个值影响MaxQueueSize，通过这个值可以动态改变线程池大小
       //配置命令，配置线程池隔离策略
       HystrixCommandProperties.Setter commandProperties= HystrixCommandProperties.Setter()
               .withExecutionIsolationStrategy(HystrixCommandProperties.ExecutionIsolationStrategy.THREAD);

       return HystrixCommand.Setter.withGroupKey(groupKey)
               .andCommandKey(commandKey)
               .andThreadPoolKey(threadPoolKey)
               .andCommandPropertiesDefaults(commandProperties)
               .andThreadPoolPropertiesDefaults(poolProperties);

   }

    @Override protected String run() throws Exception {
        return courseService.getCourse();
    }

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        GetCourseServiceCommand courseServiceCommand= new GetCourseServiceCommand();
        Future<String> future= courseServiceCommand.queue();
        System.out.println(future.get());
    }

}
